package com.dtp.logging;

import com.dtp.common.ApplicationContextHolder;
import com.dtp.common.properties.DtpProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * DtpLogging日志处理抽象类
 *
 * @author yanhom
 * @since 1.0.5
 *
 * @remark muse
 */
@Slf4j
public abstract class AbstractDtpLogging {
    protected static final String MONITOR_LOG_NAME = "DTP.MONITOR.LOG";
    private static final String CLASSPATH_PREFIX = "classpath:";
    private static final String LOGGING_PATH = "LOG.PATH";
    private static final String APP_NAME = "APP.NAME";

    static {
        try {
            DtpProperties dtpProperties = ApplicationContextHolder.getBean(DtpProperties.class);
            String logPath = dtpProperties.getLogPath();

            // 步骤1：向系统变量维护日志路径——"LOG.PATH"
            if (StringUtils.isBlank(logPath)) { // 如果没有配置spring.dynamic.tp.logPath，则默认为：{user.home}\logs；
                String userHome = System.getProperty("user.home");
                System.setProperty(LOGGING_PATH, userHome + File.separator + "logs");
            } else System.setProperty(LOGGING_PATH, logPath); //否则，以spring.dynamic.tp.logPath配置项为主

            // 步骤2：向系统变量维护应用名称——"APP.NAME"
            String appName = ApplicationContextHolder.getEnvironment().getProperty("spring.application.name");
            appName = StringUtils.isNotBlank(appName) ? appName : "application";
            System.setProperty(APP_NAME, appName);
        } catch (Exception e) {
            log.error("DynamicTp logging env init failed, if collectType is not logging, this error can be ignored.", e);
        }
    }

    /** 加载资源文件 */
    public URL getResourceUrl(String resource) throws IOException {
        // 加载CLASSPATH下指定的资源文件
        if (resource.startsWith(CLASSPATH_PREFIX)) {
            String path = resource.substring(CLASSPATH_PREFIX.length());
            ClassLoader classLoader = DtpLoggingInitializer.class.getClassLoader();
            URL url = (classLoader != null ? classLoader.getResource(path) : ClassLoader.getSystemResource(path));
            if (url == null) throw new FileNotFoundException("Cannot find file: +" + resource);
            return url;
        }

        // 加载非CLASSPATH下的资源文件
        try {
            return new URL(resource);
        } catch (MalformedURLException ex) {
            return new File(resource).toURI().toURL();
        }
    }

    /** 抽象类：实现配置加载操作，需要子类实现该方法 */
    public abstract void loadConfiguration();

    /** 抽象类：初始化LogHelper类中的monitorLogger，需要子类实现该方法 */
    public abstract void initMonitorLogger();
}
